#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <ncurses.h>
#include <locale.h>
#include <time.h>
#include <wchar.h>
#include "../include/cpu_monitor.h"
#include "../include/memory_monitor.h"
#include "../include/disk_monitor.h"
#include "../include/network_monitor.h"

#define PROGRESS_BAR_WIDTH 30
#define COLOR_PAIR_HEADER 1
#define COLOR_PAIR_CPU 2
#define COLOR_PAIR_MEM 3
#define COLOR_PAIR_DISK 4
#define COLOR_PAIR_NET 5

static volatile int running = 1;

void signal_handler(int signum) {
    (void)signum;
    running = 0;
}

// 绘制进度条
void draw_progress_bar(int y, int x, float percentage, int color_pair) {
    int width = (int)(percentage * PROGRESS_BAR_WIDTH / 100.0);
    attron(COLOR_PAIR(color_pair));
    mvprintw(y, x, "[");
    for (int i = 0; i < PROGRESS_BAR_WIDTH; i++) {
        if (i < width) {
            printw("=");
        } else {
            printw(" ");
        }
    }
    printw("] %.1f%%", percentage);
    attroff(COLOR_PAIR(color_pair));
}

// 绘制边框
void draw_box(int y, int x, int height, int width) {
    mvaddch(y, x, ACS_ULCORNER);
    mvaddch(y, x + width - 1, ACS_URCORNER);
    mvaddch(y + height - 1, x, ACS_LLCORNER);
    mvaddch(y + height - 1, x + width - 1, ACS_LRCORNER);
    
    for (int i = 1; i < width - 1; i++) {
        mvaddch(y, x + i, ACS_HLINE);
        mvaddch(y + height - 1, x + i, ACS_HLINE);
    }
    
    for (int i = 1; i < height - 1; i++) {
        mvaddch(y + i, x, ACS_VLINE);
        mvaddch(y + i, x + width - 1, ACS_VLINE);
    }
}

void print_header() {
    time_t now = time(NULL);
    char time_str[64];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&now));
    
    attron(COLOR_PAIR(COLOR_PAIR_HEADER) | A_BOLD);
    mvprintw(0, 0, "System Monitor - %s", time_str);
    mvprintw(1, 0, "Press 'q' to quit");
    attroff(COLOR_PAIR(COLOR_PAIR_HEADER) | A_BOLD);
}

void print_cpu_info(const CPU_Usage* cpu) {
    attron(COLOR_PAIR(COLOR_PAIR_CPU) | A_BOLD);
    mvprintw(3, 2, "CPU Usage");
    attroff(COLOR_PAIR(COLOR_PAIR_CPU) | A_BOLD);
    
    mvprintw(4, 4, "Total:");
    draw_progress_bar(4, 12, cpu->total, COLOR_PAIR_CPU);
    
    mvprintw(5, 4, "User:");
    draw_progress_bar(5, 12, cpu->user, COLOR_PAIR_CPU);
    
    mvprintw(6, 4, "System:");
    draw_progress_bar(6, 12, cpu->system, COLOR_PAIR_CPU);
    
    mvprintw(7, 4, "Idle:");
    draw_progress_bar(7, 12, cpu->idle, COLOR_PAIR_CPU);
}

void print_memory_info(const Memory_Usage* mem) {
    attron(COLOR_PAIR(COLOR_PAIR_MEM) | A_BOLD);
    mvprintw(9, 2, "Memory Usage");
    attroff(COLOR_PAIR(COLOR_PAIR_MEM) | A_BOLD);
    
    mvprintw(10, 4, "Total: %lu MB", mem->total / 1024 / 1024);
    mvprintw(11, 4, "Used:  %lu MB", mem->used / 1024 / 1024);
    mvprintw(12, 4, "Free:  %lu MB", mem->free / 1024 / 1024);
    
    mvprintw(13, 4, "Usage:");
    draw_progress_bar(13, 12, mem->usage_percent, COLOR_PAIR_MEM);
}

void print_disk_info(const Disk_IO_Stats* disk) {
    attron(COLOR_PAIR(COLOR_PAIR_DISK) | A_BOLD);
    mvprintw(15, 2, "Disk I/O");
    attroff(COLOR_PAIR(COLOR_PAIR_DISK) | A_BOLD);
    
    mvprintw(16, 4, "Read:  %.1f KB/s", disk->read_speed);
    mvprintw(17, 4, "Write: %.1f KB/s", disk->write_speed);
}

void print_network_info(const Network_Stats* net) {
    attron(COLOR_PAIR(COLOR_PAIR_NET) | A_BOLD);
    mvprintw(19, 2, "Network Traffic");
    attroff(COLOR_PAIR(COLOR_PAIR_NET) | A_BOLD);
    
    mvprintw(20, 4, "Receive: %.1f KB/s", net->rx_speed);
    mvprintw(21, 4, "Transmit: %.1f KB/s", net->tx_speed);
}

int main() {
    printf("系统监控程序启动中...\n");
    
    // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    // 初始化所有监控模块
    if (init_cpu_monitor() != 0) {
        printf("CPU 监控模块初始化失败\n");
        return -1;
    }
    
    if (init_memory_monitor() != 0) {
        printf("内存监控模块初始化失败\n");
        cleanup_cpu_monitor();
        return -1;
    }
    
    if (init_disk_monitor() != 0) {
        printf("磁盘监控模块初始化失败\n");
        cleanup_cpu_monitor();
        cleanup_memory_monitor();
        return -1;
    }
    
    if (init_network_monitor() != 0) {
        printf("网络监控模块初始化失败\n");
        cleanup_cpu_monitor();
        cleanup_memory_monitor();
        cleanup_disk_monitor();
        return -1;
    }
    
    // 初始化 ncurses
    initscr();
    start_color();
    use_default_colors();
    cbreak();
    noecho();
    curs_set(0);
    timeout(1000);
    
    // 设置终端编码
    set_escdelay(25);
    keypad(stdscr, TRUE);
    
    // 初始化颜色
    init_pair(COLOR_PAIR_HEADER, COLOR_WHITE, COLOR_BLUE);
    init_pair(COLOR_PAIR_CPU, COLOR_GREEN, -1);
    init_pair(COLOR_PAIR_MEM, COLOR_YELLOW, -1);
    init_pair(COLOR_PAIR_DISK, COLOR_CYAN, -1);
    init_pair(COLOR_PAIR_NET, COLOR_MAGENTA, -1);
    
    while (running) {
        clear();
        
        // 绘制主边框
        draw_box(0, 0, 23, 60);
        
        print_header();
        
        // 获取系统信息
        CPU_Usage cpu_usage = get_cpu_usage();
        Memory_Usage mem_usage = get_memory_usage();
        Disk_IO_Stats disk_stats = get_disk_io_stats();
        Network_Stats net_stats = get_network_stats();
        
        // 打印系统信息
        print_cpu_info(&cpu_usage);
        print_memory_info(&mem_usage);
        print_disk_info(&disk_stats);
        print_network_info(&net_stats);
        
        refresh();
        
        // 检查是否按下 q 键退出
        int ch = getch();
        if (ch == 'q' || ch == 'Q') {
            running = 0;
        }
        
        sleep(1);  // 每秒更新一次
    }
    
    // 清理 ncurses
    clear();
    refresh();
    endwin();
    
    // 清理所有监控模块
    cleanup_cpu_monitor();
    cleanup_memory_monitor();
    cleanup_disk_monitor();
    cleanup_network_monitor();
    
    printf("系统监控程序已退出\n");
    return 0;
} 